﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using ST.Buz.Base;
using ST.Buz.Base.Entity;
using ST.Buz.Base.Enums;
using ST.Buz.Base.ViewModel;
using ST.Common.Util;
using ST.Common.Util.Model;
using ST.Common.Util.Mvc;
using System;
using System.Collections.Generic;
using Microsoft.Data.SqlClient;
using System.Linq;
using Microsoft.Extensions.Hosting;
using System.Threading.Tasks;
using System.Threading;
using System.ComponentModel.Design;
using Microsoft.Extensions.DependencyInjection;

namespace ST.Buz.Service
{
    public partial class HostedServiceApplicationLifetime : IHostedService
    {
        private readonly ILogger logger;
        private readonly IHostApplicationLifetime applicationLifetime;
        private readonly IServiceProvider serviceProvider;

        public HostedServiceApplicationLifetime(
            IServiceProvider _serviceProvider,
            ILogger<HostedServiceApplicationLifetime> _logger,
            IHostApplicationLifetime _applicationLifetime)
        {
            logger = _logger;
            applicationLifetime = _applicationLifetime;

            serviceProvider = _serviceProvider;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            applicationLifetime.ApplicationStarted.Register(OnStarted);
            applicationLifetime.ApplicationStopping.Register(OnStopping);
            applicationLifetime.ApplicationStopped.Register(OnStopped);

            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }

        private void OnStarted()
        {
            logger.LogInformation("OnStarted has been called.");

            //using (var scope = serviceProvider.CreateScope())
            //{
            //    var service = scope.ServiceProvider.GetRequiredService<IServicePartnerCat>();
            //    service.Add(new IMS_PartnerCat() { Name = "" });
            //}
        }

        private void OnStopping()
        {
            logger.LogInformation("OnStopping has been called.");

            // Perform on-stopping activities here
        }

        private void OnStopped()
        {
            logger.LogInformation("OnStopped has been called.");
        }
    }
}